import React, { useEffect, useMemo, useRef, useState } from 'react';
import styled from 'styled-components';

const TitleLayout = styled.div`
  &.ife-ellipsis__nowrap {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &.ife-ellipsis__line-clamp {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
`;

interface Props {
  lineClamp?: number;
  content?: string;
  title?: string;
  isTitle?: boolean;
  callback?: (flag?: boolean) => void;
}
export const SuperTitle: React.FC<Props> = (props) => {
  const { lineClamp = 1, content = '', title, isTitle = true, callback } = props;
  const ref: any = useRef(null);

  const [titleString, setTitleString] = useState('');

  // 判断是否超出
  const isEllipsis = useMemo(() => {
    if (ref?.current) {
      const { clientWidth, scrollWidth, clientHeight, scrollHeight } = ref.current;

      console.log(clientHeight, scrollHeight);
      if (lineClamp > 1) {
        return clientHeight < scrollHeight;
      } else {
        return clientWidth < scrollWidth;
      }
    }
  }, [lineClamp, ref]);

  useEffect(() => {
    const flag = isEllipsis;
    if (flag && isTitle && (title || content)) {
      setTitleString(title || content);
    }
    if (callback) {
      callback(flag);
    }
  }, [title, content, isTitle, isEllipsis]);

  return (
    <TitleLayout
      style={{ WebkitLineClamp: lineClamp }}
      className={lineClamp > 1 ? 'ife-ellipsis__line-clamp' : 'ife-ellipsis__nowrap'}
      title={titleString}
    >
      {content && <span>{content}</span>}
    </TitleLayout>
  );
};
